<?php
	/*
		this file parses the post data and saves it to the database
	*/
	require_once("../functions.php");
	
	function parseCompChildren($compChild,$comp_jsonId, $diag_jsonId, $db_key){
		if($compChild==null || !is_object($compChild)){
			return;
		}
		
		$jsonId = $compChild->id;
		$parentType = $compChild->parentType;
		$type = mysql_real_escape_string($compChild->type);
		$childType = mysql_real_escape_string($compChild->childType);
		$modifier = $compChild->modifier;
		$name = mysql_real_escape_string($compChild->name);
		$parameters = mysql_real_escape_string($compChild->parameters);
		
		$sql = "SELECT c.id FROM component c,diagram d, project p WHERE p.id=$db_key AND d.jsonId = '$diag_jsonId' AND d.project_id=p.id AND  c.jsonId='$comp_jsonId' AND c.diagram_id=d.id";
		
		$result = mysql_query($sql) or die("parseCompChildren(): " + mysql_error());
		$row = mysql_fetch_array($result);
		mysql_free_result($result);
		$compId = $row["id"];
		
		$sql2 = "INSERT INTO children (jsonId, parentType, childType, type, modifier, name, parameters, component_id) VALUES " . 
				"('$jsonId', '$parentType', '$childType', '$type','$modifier', '$name', '$parameters', $compId)";
		
		appendDebug($sql2);
		
		mysql_query($sql2) or die("parseCompChildren(): " + $sql2 + "<br />" + mysql_error());
		
	}
	
	function parseDiagram($diagram, $db_key){
		//diagram
		$name = isset($diagram->name) ? mysql_real_escape_string($diagram->name) : "";
		$dJsonId = $diagram->id;
		$type = $diagram->umltype;
		$width = $diagram->width;
		$height = $diagram->height;
		$sortOrder = $diagram->sort_order;
		$custom = isset($diagram->custom) ? mysql_real_escape_string($diagram->custom) : "";
		$desc = isset($diagram->description) ? mysql_real_escape_string($diagram->description) : "";
		
		$sql = "INSERT INTO diagram (name,jsonId, diagramType, width, height,description, sortOrder, custom, project_id) values ('$name', '$dJsonId','$type', $width, $height, '$desc', $sortOrder, '$custom', $db_key)";
		mysql_query($sql) or die("New diagram :" . mysql_error());
		
		$result = mysql_query("SELECT MAX(d.id) id FROM diagram d, project p WHERE d.project_id = p.id AND p.id=$db_key") or die("Select diagram: " . mysql_error());
		$row = mysql_fetch_array($result);
		$diagram_id = $row["id"];
		
		//components
		$components = (isset($diagram->children)) ? $diagram->children : null;
		if(is_array($components)){
			for($j=0; $components!=null && $j<count($components); $j++){
				$component = $components[$j];
				
				$name = isset($component->name) ? mysql_real_escape_string($component->name) : "";
				$type = $component->umltype;
				$jsonId = $component->id;
				$x = $component->x;
				$y = $component->y;
				$sortOrder = $component->sortOrder;
				$label = isset($component->label) ? mysql_real_escape_string($component->label) : "";
				$custom = isset($component->custom) ? mysql_real_escape_string($component->custom) : "";
				$desc = isset($component->description) ? mysql_real_escape_string($component->description) : "";
				
				$sql = "INSERT INTO component (name, jsonId, componentType, x, y, sortOrder, label, description, custom, diagram_id) values ('$name', '$jsonId','$type', $x, $y, $sortOrder, '$label', '$desc', '$custom', $diagram_id)";
				
				mysql_query($sql) or die("New component: " . mysql_error());
				
				if(isset($component->comp_children)){
					parseCompChildren($component->comp_children, $jsonId, $dJsonId, $db_key);
				}
			}
		}else if($components !=null){
			$component = $components;
			
			$name = isset($component->name) ? mysql_real_escape_string($component->name) : "";
			$type = $component->umltype;
			$jsonId = $component->id;
			$x = $component->x;
			$y = $component->y;
			$sortOrder = $component->sortOrder;
			$label = isset($component->label) ? mysql_real_escape_string($component->label) : "";
			$custom = isset($component->custom) ? mysql_real_escape_string($component->custom) : "";
			$desc = isset($component->description) ? mysql_real_escape_string($component->description) : "";
			
			$sql = "INSERT INTO component (name, jsonId, componentType, x, y, sortOrder, label, description, custom, diagram_id) 
					values ('$name', '$jsonId','$type', $x, $y, $sortOrder, '$label', '$desc', '$custom', $diagram_id)";
			
			mysql_query($sql) or die("New component: " . mysql_error());
			
			if(isset($component->comp_children)){
				parseCompChildren($component->comp_children, $jsonId, $dJsonId, $db_key);
			}
		}
		
		//connections
		$connections = (isset($diagram->connections)) ? $diagram->connections : null;
		if(is_array($connections)){
			for($j=0; $connections!=null && $j<count($connections); $j++){
				$connection = $connections[$j];
				
				$name = isset($connection->name) ? mysql_real_escape_string($connection->name) : "";
				$type = $connection->umltype;
				$comp1_jsonId = $connection->ref1_id;
				$comp2_jsonId = $connection->ref2_id;
				$jsonId = $connection->id;
				$type = $connection->umltype;
				
				$card1 = $connection->cardinality1;
				$card2 = $connection->cardinality2;
				$comp1_dir = $connection->ref1_dir;
				$comp2_dir = $connection->ref2_dir;
				$stereotype = isset($connection->stereotype) ? mysql_real_escape_string($connection->stereotype) : "";
				$custom = isset($connection->custom) ? mysql_real_escape_string($connection->custom) : "";
				$desc = isset($connection->description) ? mysql_real_escape_string($connection->description) : "";
				
				$sql = "SELECT c.id,c.jsonId FROM component c, diagram d, project p where (c.jsonId = '$comp1_jsonId' or c.jsonId = '$comp2_jsonId') and (c.diagram_id = d.id and d.project_id = $db_key)";
				
				$result = mysql_query($sql) or die("Select components" . mysql_error());
				
				$comp1_row = mysql_fetch_array($result);
				$comp2_row = mysql_fetch_array($result);
								
				if(strcmp($comp1_jsonId, $comp1_row["jsonId"])==0){
					$comp1_id = $comp1_row["id"];
					$comp2_id = $comp2_row["id"];
					
					$comp1_jsonId = $comp1_row["jsonId"];
					$comp2_jsonId = $comp2_row["jsonId"];
				}else{
					$comp2_id = $comp1_row["id"];
					$comp1_id = $comp2_row["id"];
					
					$comp2_jsonId = $comp1_row["jsonId"];
					$comp1_jsonId = $comp2_row["jsonId"];
				}
				
				$sql = "INSERT INTO connection (component1_id, component2_id, jsonId, name, component1_dir, component2_dir, connectionType, cardinality1, cardinality2, component1_jsonId, component2_jsonId, stereotype, description, custom) 
										values ($comp1_id, $comp2_id, '$jsonId', '$name', '$comp1_dir', '$comp2_dir', '$type', '$card1', '$card2', '$comp1_jsonId', '$comp2_jsonId', '$stereotype', '$desc', '$custom')";
				
				mysql_query($sql) or die("New connection" . mysql_error() . "<br />" .$sql);
			}
		}else if($connections!=null){
			$connection = $connections;
			
			$name = isset($connection->name) ? mysql_real_escape_string($connection->name) : "";
			$type = $connection->umltype;
			$comp1_jsonId = $connection->ref1_id;
			$comp2_jsonId = $connection->ref2_id;
			$jsonId = $connection->id;
			$type = $connection->umltype;
			
			$card1 = $connection->cardinality1;
			$card2 = $connection->cardinality2;
			$comp1_dir = $connection->ref1_dir;
			$comp2_dir = $connection->ref2_dir;
			$stereotype = isset($connection->stereotype) ? mysql_real_escape_string($connection->stereotype) : "";
			$custom = isset($connection->custom) ? mysql_real_escape_string($connection->custom) : "";
			$desc = isset($connection->description) ? mysql_real_escape_string($connection->description) : "";
			
			$sql = "SELECT c.id,c.jsonId FROM component c, diagram d, project p where (c.jsonId = '$comp1_jsonId' or c.jsonId = '$comp2_jsonId') and (c.diagram_id = d.id and d.project_id = $db_key)";
			
			$result = mysql_query($sql) or die("Select components" . mysql_error());
			
			$comp1_row = mysql_fetch_array($result);
			$comp2_row = mysql_fetch_array($result);
			
			if(strcmp($comp1_jsonId, $comp1_row["jsonId"])==0){
				$comp1_id = $comp1_row["id"];
				$comp2_id = $comp2_row["id"];
				
				$comp1_jsonId = $comp1_row["jsonId"];
				$comp2_jsonId = $comp2_row["jsonId"];
			}else{
				$comp2_id = $comp1_row["id"];
				$comp1_id = $comp2_row["id"];
				
				$comp2_jsonId = $comp1_row["jsonId"];
				$comp1_jsonId = $comp2_row["jsonId"];
			}
			
			$sql = "INSERT INTO connection (component1_id, component2_id, jsonId, name, component1_dir, component2_dir, connectionType, cardinality1, cardinality2, component1_jsonId, component2_jsonId, stereotype, description, custom) 
									values ($comp1_id, $comp2_id, '$jsonId', '$name', '$comp1_dir', '$comp2_dir', '$type', '$card1', '$card2', '$comp1_jsonId', '$comp2_jsonId', '$stereotype', '$desc', '$custom')";
			
			mysql_query($sql) or die("New connection" . mysql_error() . "<br />" .$sql);
		}
	}
	
	function newProject($proj){
		$name = mysql_real_escape_string($proj->name);
		$uid = getUserId($_SESSION["username"]);
		$sql = "INSERT INTO project (name, dateCreated, description, isValid, user_id, diagramCounter, componentCounter, connectionCounter,componentChildrenCounter) 
							VALUES ('$name', curdate(), '', true, $uid, " . $proj->diag_counter . ", " . $proj->comp_counter . ", ". $proj->conn_counter .", ". $proj->comp_children_counter . ")";
		
		mysql_query($sql) or die("New project: " . mysql_error());
		$result = mysql_query("select max(id) id from project") or die("Select project: " . mysql_error());
		$row = mysql_fetch_array($result);
		
		return $row["id"];
	}
	
	function deleteDiagramsAndDependencies($projId){
		//delete one by one
		
		$sql = "SELECT cn.component1_id, cn.component2_id FROM CONNECTION cn, component c, diagram d, project p WHERE p.id=$projId AND p.id=d.project_id AND d.id = c.diagram_id AND (c.id = cn.component1_id OR c.id = cn.component2_id) GROUP BY cn.component1_id, cn.component2_id";	//select connections
		$result = mysql_query($sql) or die ("select connections to delete: " . $sql . ": " . mysql_error());
		while($row = mysql_fetch_array($result)){
			mysql_query("DELETE FROM connection where component1_id=" . $row["component1_id"] . " AND component2_id=" . $row["component2_id"]) or die("delete connection: " . mysql_error()) ;
		}
		mysql_free_result($result);
		
		$sql = "SELECT ch.id FROM children ch, component c, diagram d, project p WHERE p.id=$projId AND p.id=d.project_id AND d.id = c.diagram_id AND c.id = ch.component_id";	//select children
		$result = mysql_query($sql) or die ("select connections to delete: " . $sql . ": " . mysql_error());
		while($row = mysql_fetch_array($result)){
			mysql_query("DELETE FROM children where id=" . $row["id"]) or die("delete children: " . mysql_error()) ;
		}
		mysql_free_result($result);
		
		$sql = "SELECT c.id FROM component c, diagram d, project p WHERE p.id=$projId AND p.id=d.project_id AND d.id = c.diagram_id";	//select components
		$result = mysql_query($sql) or die ("select connections to delete: " . $sql . ": " . mysql_error());
		while($row = mysql_fetch_array($result)){
			mysql_query("DELETE FROM component where id=" . $row["id"]) or die("delete component: " . mysql_error()) ;
		}
		mysql_free_result($result);
		
		$sql = "delete from diagram where project_id=$projId";		//delete diagrams
		mysql_query($sql) or die("Delete diagrams: " . $sql . ": " . mysql_error());
		appendDebug("Finsihed deleting");
	}
	
	function updateProject($proj){
		if($proj->db_key==1 || $proj->db_key==2){
			appendInfo("Attempted to save a default project.");
			return;		//prevent edits of the default projects
		}
		
		deleteDiagramsAndDependencies(mysql_real_escape_string($proj->db_key));
		
		$name = mysql_real_escape_string($proj->name);
		$sql = "update project set name='$name', dateModified=curdate(), diagramCounter=". $proj->diag_counter ." , componentCounter=".$proj->comp_counter.", connectionCounter=".$proj->conn_counter .", componentChildrenCounter=". $proj->comp_children_counter ." where id = " . $proj->db_key;
		mysql_query($sql) or die("Update project:" . mysql_error());
	}
	
	//------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	
	if(!isLoggedIn()){
		header("location:index.php?message=".urlencode("Please login first."));
		die();
	}
	
	if(!isset($_POST["data"])){
		echo "No data";
		die();
	}
	
	connectToDB();
	
	$tab = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$obj = json_decode($_POST["data"]);
	
	$proj = $obj->items[0];
	$db_key = $proj->db_key;
	appendDebug("DB kdey: " . $db_key);
	if($db_key>0){
		appendDebug("update project");
		updateProject($proj);
	}else{
		appendDebug("new project");
		$db_key = newProject($proj);
	}
	
	if($db_key>2){
		$diagrams = (isset($proj->children)) ? $proj->children : null;
		
		echo $db_key;
		
		if(is_array($diagrams)){
			for($i=0; $diagrams!=null && $i<count($diagrams); $i++){
				parseDiagram($diagrams[$i], $db_key);
			}
		}else if($diagrams!=null){
			parseDiagram($diagrams, $db_key);
		}	
	}
	
	switch(json_last_error()){
		case JSON_ERROR_DEPTH:
			appendDebug('PHP JSON decoding error : Maximum stack depth exceeded.');
		break;
		case JSON_ERROR_CTRL_CHAR:
			appendDebug('PHP JSON decoding error : Unexpected control character found.');
		break;
		case JSON_ERROR_SYNTAX:
			appendDebug('PHP JSON decoding error : Syntax error, malformed JSON.');
		break;
	}
?>